import { View,Text } from '@tarojs/components'
import React,{ useState,useRef } from 'react'
import { useEffect } from 'react'
import './index.scss'

export default function Cashier(props) {
  const {time,autoStart} = props
  const timer = useRef('')
  const timeData = useRef({
    remain: 0,
    day: 0,
    hour: 0,
    minute: 0,
    second: 0
  })
  const [day,setDay] = useState(0)
  const [hour,setHour] = useState(0)
  const [minute,setMinute] = useState(0)
  const [second,setSecond] = useState(0)
  useEffect(()=>{
    reset()
  },[time])
  useEffect(()=>{
    return ()=>{
      pause()
    }
  },[])
  const updateTimeData = () => {
    let t = timeData.current.remain;
    timeData.current.day = Math.floor(t / 1000 / 60 / 60 / 24);
    timeData.current.hour = Math.floor((t / 1000 / 60 / 60) % 24);
    timeData.current.minute = Math.floor((t / 1000 / 60) % 60);
    timeData.current.second = Math.floor((t / 1000) % 60);
    setDay(Math.floor(t / 1000 / 60 / 60 / 24))
    setHour(Math.floor((t / 1000 / 60 / 60) % 24))
    setMinute(Math.floor((t / 1000 / 60) % 60))
    setSecond(Math.floor((t / 1000) % 60))
  }
  
  // 开启倒计时
  const startTimer = ()=> {
    if (timer.current) {
      clearInterval(timer.current);
    }
    if(timeData.current.remain < 1000) {
      return
    }
    timer.current = setInterval(() => {
      timeData.current.remain -= 1000;
      updateTimeData()
      if (timeData.current.remain < 1000) {
        pause()
        onFinish(true)
      }
    }, 1000);
  }
  const reset = () => {
    timeData.current.remain = time;
    updateTimeData();
    if(autoStart) {
      start()
    }
  }
  
  const pause = ()=> {
    if(timer.current) {
      clearInterval(timer.current);
      timer.current = null
    }
  }
  // 开始倒计时
  const start = ()=> {
    if(timer.current) {
      return
    }
    startTimer();		
  }

  return (
    <View className='countdown-timer'>
      <View>剩余 <Text class="span">{minute>9?minute:'0'+minute}</Text>:<Text class="span">{second>9?second:'0'+second}</Text></View>
    </View>
  )
}
